<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Product extends AdminBackEndController {
    public function __construct() {
        parent::__construct();
        $this->load->model('repo/product_model', 'product_model');
        $this->load->model('repo/category_model', 'category_model');
    }

    private function intialPaging() {
        $this->load->library('mypaging');
        $this->mypaging->setLimit(PRODUCT_LIMIT);
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function index($pageIndex = 1) {
        $this->intialPaging();
        $this->mypaging->setCount($this->product_model->countAllProduct(array('b.is_avatar'=>1)));
        $this->mypaging->setMainURL(admin_product_paging_url());
        $pagingBar = $this->mypaging->getBar($pageIndex);
        $offset = ($pageIndex - 1) * PRODUCT_LIMIT;
        $aProduct = $this->product_model->getProductList(PRODUCT_LIMIT, $offset, array('b.is_avatar'=>1));
        $aShopCategory = $this->category_model->getCategories();
        $aReturn = array(
            'pageTitle' => 'Sản phẩm',
            'aProduct' => $aProduct,
            'aShopCategory' => $aShopCategory,
            'pagingBar' => $pagingBar
            );
        $this->renderView('backend/admin/product/index', $aReturn);
    }

    public function search($pageIndex = 1) {
        $searchkey = $this->input->get('s', true);
        $this->intialPaging();
        $this->mypaging->setCount($this->product_model->countAllSearchProduct($searchkey));
        $this->mypaging->setMainURL(admin_product_search_paging_url());
        $pagingBar = $this->mypaging->getBar($pageIndex, array('s' => $searchkey));
        $offset = ($pageIndex - 1) * PRODUCT_LIMIT;
        $aProduct = $this->product_model->searchProductAdmin(PRODUCT_LIMIT, $offset, $searchkey);
        $aReturn = array(
            'pageTitle' => 'Sản phẩm',
            'aProduct' => $aProduct,
            'pagingBar' => $pagingBar,
            'searchkey' => $searchkey);
        $this->renderView('backend/admin/product/index', $aReturn);
    }

    public function get($slug) {
        $product = $this->product_model->getProduct($slug, array('a.slug'=> $slug));
        if (count($product) == 0) {
            show_404();
        }
        $aProductCate = $this->category_model->getCategories();
        $aProductInSet = $this->product_model->getProductInSet($product->product_id);
        $aReturn = array(
            'pageTitle' => $product->product_title,
            'product' => $product,
            'aProductCate' => $aProductCate,
            'aProductInSet' => $aProductInSet,
            'action_link' => "cap-nhat");

        $this->renderView('backend/admin/product/single', $aReturn);
    }

    public function flashUpdate() {
        $aResult = array();
        $product = $this->input->post('product');
        if(!isset($product['id'])){
            $aResult = array(
                'code' => 0,
                'title'=> $this->lang->line('system_error')
                );
            $this->renderJSON($aResult);
            return;
        }

        $id = $this->encrypt->decode($product['id']);
        if($id===false){
            $aResult = array(
                'code' => 0,
                'text' => '<ul>'.$this->lang->line('system_error').'</ul>'
                );
            $this->renderJSON($aResult);
            return;
        }

        $result = false;
        $options = array();
        $date = get_current_date();

        if(isset($product['home_flg'])){
            if($product['home_flg']==ON){
                $product['home_flg']==OFF;
            } else {
                $product['home_flg']==OFF;
            }
            $options = array('home_flg'=>$product['home_flg'], 'updated_at'=>$date);
        }

        if(isset($product['delete_flg'])){
            if($product['delete_flg']==1){
                $options = array('deleted_at'=>$date);
            } else {
                $options = array('updated_at'=>$date, 'deleted_at'=>NULL);
            }
        }

        if(isset($product['active_flg'])){
            if($product['active_flg']==1){
                $options = array('updated_at'=>$date, 'active_flg'=>1);
            } else {
                $options = array('updated_at'=>$date, 'active_flg'=>0);
            }
        }

        if(isset($product['highlight_flg'])){
            if($product['highlight_flg']==1){
                $options = array('updated_at'=>$date, 'highlight_flg'=>1);
            } else {
                $options = array('updated_at'=>$date, 'highlight_flg'=>0);
            }
        }

        if(count($options)>0){
            $result = $this->product_model->updateProduct($id, $options);
        }

        if($result){
            $aResult = array('code' => 1, 'text' => $this->lang->line('update_success'));
        } else {
            $aResult = array(
                'code' => 0,
                'title'=> $this->lang->line('system_error')
                );
        }
        $this->renderJSON($aResult);
        return;
    }

    private function setValidate($aDetail) {
        $this->form_validation->set_rules('product[title]',        'lang:product_title', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('product[slug]',         'lang:product_slug',  'trim|required|callback_slug_check|xss_clean');
        foreach ($aDetail as $index => $d) {
            //set more lang
            $this->lang->language['product_deltail_code_'       .$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_code');
            $this->lang->language['product_deltail_price_old_'  .$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_price_old');
            $this->lang->language['product_deltail_price_new_'  .$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_price_new');
            $this->lang->language['product_deltail_description_'.$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_description');

            $this->form_validation->set_rules("product_detail[$index][code]",       'lang:product_deltail_code_'       .$index, 'trim|required|max_length[50]|xss_clean');
            $this->form_validation->set_rules("product_detail[$index][price_old]",  'lang:product_deltail_price_old_'  .$index, 'trim|callback_blank_numeric_check|xss_clean');
            $this->form_validation->set_rules("product_detail[$index][price_new]",  'lang:product_deltail_price_new_'  .$index, 'trim|callback_blank_numeric_check|xss_clean');
            $this->form_validation->set_rules("product_detail[$index][description]",'lang:product_deltail_description_'.$index, 'trim|max_length['.CONTENT_LENGTH.']|xss_clean');
        }

        $this->form_validation->set_error_delimiters('<li>', '</li>');
    }

    public function fullUpdate(){
        $aResult = array();
        $data = array();
        $date = new DateTime();
        $product = $this->input->post('product', true);
        $aProductDetail = $this->input->post('product_detail', true);
        $this->setValidate($aProductDetail);
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>',
                );
            $this->renderJSON($aResult);
            return;
        }

        $productTemp        = $this->input->post('product');
        $aProductDetailTemp = $this->input->post('product_detail');
        $productId          = $this->encrypt->decode($productTemp['id']);
        $shopId             = $this->encrypt->decode($productTemp['shop_id']);
        if ($productId == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('shop_category_id_invalid') . '</li></ul>');

            $this->renderJSON($aResult);
            return;
        }

        //check exist product
        $this->load->model('repo/shop_product_model', 'shop_product_model');
        $option = array(
            'shop_id' => $shopId,
            'title'   => $product['title'],
            'slug'    => $product['slug']
        );
        $iExist = $this->shop_product_model->checkProductExist($option, $productId);

        if ($iExist > 0) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('product_exists') . '</li></ul>',
                );
            $this->renderJSON($aResult);
            return;
        }

        //check already exist detail code
        $liCode = "";
        foreach ($aProductDetail as $index => $pdt) {
            $option['code'] = $pdt['code'];
            $productDetailId = $this->encrypt->decode($aProductDetailTemp[$index]['id']);
            $iExistCode = $this->shop_product_model->checkProductCodeExist($option, $productDetailId);
            if ($iExistCode > 0) {
                $liCode .= '<li>' . sprintf($this->lang->line('product_detail_code_exists'), $pdt['code']) . '</li>';
            }
        }
        if ($liCode != '') {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . $liCode . '</ul>',
                );
            $this->renderJSON($aResult);
            return;
        }

        if (isset($product['delete_flg']) && $product['delete_flg'] == 1) {
            $product['deleted_at'] = $date->format(DATE_TIME_FORMAT);
        } else {
            $product['deleted_at'] = NULL;
            $product['updated_at'] = $date->format(DATE_TIME_FORMAT);
        }

        if (isset($product['active_flg']) && $product['active_flg'] == 1) {
            $product['active_flg'] = 1;
        } else {
            $product['active_flg'] = 0;
        }

        unset($product['delete_flg']);
        unset($product['id']);
        unset($product['product_cate']);
        unset($product['shop_id']);

        $data['product'] = $product;

        //product_detail area
        $data['product_detail_update'] = array();
        $data['product_detail_new'] = array();

        foreach ($aProductDetail as $index => $pdt) {
            // set flag
            if (isset($pdt['delete_flg']) && $pdt['delete_flg'] == 1) {
                $pdt['deleted_at'] = $date->format(DATE_TIME_FORMAT);
            } else {
                $pdt['deleted_at'] = NULL;
                $pdt['updated_at'] = $date->format(DATE_TIME_FORMAT);
            }
            unset($pdt['delete_flg']);

            //set avatar
            if(isset($pdt['is_avatar']) && $pdt['is_avatar']==1){
                $pdt['is_avatar']=1;
            } else {
                $pdt['is_avatar']=0;
            }

            // set case new/update
            if (isset($pdt['id'])) {
                $productDetailId = $this->encrypt->decode($aProductDetailTemp[$index]['id']);
                unset($pdt['id']);
                $data['product_detail_update'][$productDetailId] = $pdt;
            } else {
                $pdt['product_id'] = $productId;
                $pdt['created_at'] = $date->format(DATE_TIME_FORMAT);
                array_push($data['product_detail_new'], $pdt);
            }
        }
        $result = $this->shop_product_model->update($productId, $data);
        if ($result) {
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('update_success'),
                'href' => admin_product_single_url($product['slug'])
                );
        } else {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error'));
        }

        $this->renderJSON($aResult);
    }
}
?>